// src/utils/task.ts
// 任务状态相关工具函数

// 获取状态显示文本
export const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    processing: '处理中',
    success: '成功',
    failed: '失败',
  }
  return statusMap[status] || status
}

// 获取状态颜色
export const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    processing: 'warning',
    success: 'success',
    failed: 'danger',
  }
  return colorMap[status] || 'info'
}

// 格式化时间
export const formatTime = (time: string): string => {
  return new Date(time).toLocaleString('zh-CN')
}

// 轮询检查任务状态
export const pollTaskStatus = async (
  taskId: string,
  fetchTask: (id: string) => Promise<any>,
  onSuccess?: () => void,
  onError?: (error: string) => void,
  maxAttempts: number = 30,
): Promise<void> => {
  let attempts = 0

  // 添加参数验证
  if (!taskId) {
    onError?.('任务ID不能为空')
    return
  }

  const checkStatus = async () => {
    attempts++
    console.log(`检查任务状态: ${taskId}, 尝试次数: ${attempts}`) // 添加日志

    try {
      const task = await fetchTask(taskId)

      if (task.status === 'success') {
        console.log('任务处理成功')
        onSuccess?.()
        return
      }

      if (task.status === 'failed') {
        console.log('任务处理失败:', task.errorMessage)
        onError?.(task.errorMessage || '任务处理失败')
        return
      }

      // 如果还没完成，继续轮询
      if (attempts < maxAttempts) {
        console.log('任务处理中，继续轮询...')
        setTimeout(checkStatus, 2000) // 2秒后再次检查
      } else {
        console.log('任务处理超时')
        onError?.('任务处理超时')
      }
    } catch (error) {
      console.error('检查任务状态出错:', error)
      if (attempts < maxAttempts) {
        setTimeout(checkStatus, 2000)
      } else {
        onError?.('检查任务状态失败')
      }
    }
  }

  await checkStatus()
}
